﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Web;
using Kugar.Core.ExtMethod;
using Kugar.Core.Web;
using Kugar.UI.Web.AdminLTE.Enums;
using Kugar.UI.Web.AdminLTE.Helpers;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Razor;
using ViewContext = Microsoft.AspNetCore.Mvc.Rendering.ViewContext;

namespace Kugar.UI.Web.AdminLTE.PageControls.PageCommon
{
    public class PageCommon_Tab:ContainerBase
    {
        private TabSideEnum _side = TabSideEnum.Top;
        private List<(string title,string id,bool isactive,string onActiveValue)> _pageTitles=new List<(string title, string id, bool isactive, string onActiveValue)>(5);
        private string _activePageID = "";
        private string _leftTabWidth = "52px";
        private string _urlKey = "";

        public PageCommon_Tab(ViewContext viewContext) : base(viewContext)
        {
            this.Css("nav-tabs-custom");
        }

        /// <summary>
        /// 用于设置点击tabpage之后,url自动添加一个querystring的key,用于自动记录当tagpage,下次刷新时,自动设置
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public PageCommon_Tab QueryKey(string key)
        {
            _urlKey = key;

            return this;
        }

        /// <summary>
        /// 添加一个tab页,并手动设置是否为当前页面
        /// </summary>
        /// <param name="title"></param>
        /// <param name="id">tabpage的id</param>
        /// <param name="isActived">是否为当前页面</param>
        /// <param name="onActiveValue">切换到当前页面后,url中urlkey对应的值改为该参数值,默认为id</param>
        /// <returns></returns>
        public PageCommon_Tab AddPage(string title, string id,bool isActived,string onActiveValue="")
        {
            _pageTitles.Add((title,id,isActived, onActiveValue.IfEmptyOrWhileSpace(id)));

            return this;
        }

        /// <summary>
        /// 添加一个页面,并根据url中的urlkey参数,判断是否与onActiveValue相等,相等的,自动为当前页面
        /// </summary>
        /// <param name="title"></param>
        /// <param name="id">tabpage的id,<b>一定要使用英文id</b></param>
        /// <param name="onActiveValue">切换到当前页面后,url中urlkey对应的值改为该参数值,默认为id</param>
        /// <returns></returns>
        public PageCommon_Tab AddPage(string title, string id,string onActiveValue = "")
        {
            onActiveValue=onActiveValue.IfEmptyOrWhileSpace(id);

            var isActived = false;

            if (!string.IsNullOrEmpty(_urlKey) && !string.IsNullOrWhiteSpace(onActiveValue))
            {
                var v = ViewContext.HttpContext.Request.GetString(_urlKey);

                isActived = onActiveValue.CompareTo(v, true);
            }

            _pageTitles.Add((title, id, isActived, onActiveValue.IfEmptyOrWhileSpace(id)));

            return this;
        }

        public PageCommon_Tab Side(TabSideEnum side)
        {
            _side = side;

            return this;
        }
        
        public PageCommon_Tab LeftTabWidth(int width)
        {
            _leftTabWidth = $"{width}px";

            return this;
        }

        public TabContent RenderPage(string id,string activeScript="",string unaciveScript="")
        {
            //bool isactive = _pageTitles.FirstOrDefault(x => x.id == id).isactive;
            
            var content=new TabContent(id, id== _activePageID,_urlKey, ViewContext);
            content.ActiveScript(activeScript).UnActiveScript(unaciveScript);

            return content;
        }

        public HtmlString RenderPage(string id, Func<PageCommon_Tab, HelperResult> contentHelper, string activeScript = "", string unaciveScript = "")
        {
            bool isactive = _pageTitles.FirstOrDefault(x => x.id == id).isactive;

            ViewContext.Writer.WriteLine($"<div class=\"tab-pane {isactive.If("active")}\" {(string.IsNullOrWhiteSpace(activeScript)?"":$"active=\"{activeScript}\"")} {(string.IsNullOrWhiteSpace(unaciveScript) ? "" : $"unactive=\"{unaciveScript}\"")} id=\"{id}\">");

            contentHelper(this).WriteTo(ViewContext.Writer,HtmlEncoder.Default);
 
            ViewContext.Writer.WriteLine("</div>");
            
            return HtmlString.Empty;
        }

        public override void Dispose()
        {
            WriteClearfix();
            
            ViewContext.Writer.WriteLine("<!-- /.tab-content --> </div>");

            if (_side == TabSideEnum.Bottom)
            {
                ViewContext.Writer.WriteLine("<ul class=\"nav nav-tabs\">");

                foreach (var titleItem in _pageTitles)
                {
                    ViewContext.Writer.WriteLine($"<li class=\"{(titleItem.id == _activePageID).If("active")}\"><a href=\"#{titleItem.id}\" data-toggle=\"tab\">{titleItem.title}</a></li>");
                }

                ViewContext.Writer.WriteLine("</ul>");
            }

            ViewContext.Writer.WriteLine("</div>");

            if (_withOuterBorder)
            {
                ViewContext.Writer.WriteLine($"</div> <!-- outer border -->");
            }
        }

        internal override ContainerBase RenderInternal()
        {
            switch (_side)
            {
                case TabSideEnum.Top:
                    break;
                case TabSideEnum.Bottom:
                {
                    this.Css("tab-bottom");
                }
                    break;
                case TabSideEnum.Left:
                {
                    this.Css("tabs-left");
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if (_pageTitles.Any(x => x.isactive))
            {
                _activePageID = _pageTitles.FirstOrDefault(x => x.isactive).id;
            }
            else if(_pageTitles.HasData())
            {
                _activePageID = _pageTitles[0].id;
            }

            if (_withOuterBorder)
            {
                ViewContext.Writer.WriteLine($"<div class=\"{_outerBorderCss}\">");
            }

            ViewContext.Writer.WriteLine($"<div {Attributes}>");
            
            if (_side!= TabSideEnum.Bottom)
            {
                ViewContext.Writer.WriteLine($"<ul class=\"nav nav-tabs\" style=\"{(_side == TabSideEnum.Left ? $"width:{_leftTabWidth}" : "")}\">");

                foreach (var titleItem in _pageTitles)
                {
                    ViewContext.Writer.WriteLine($"<li class=\"{(titleItem.id== _activePageID).If("active")}\"><a href=\"#{titleItem.id}\" data-toggle=\"tab\">{titleItem.title}</a></li>");
                }

                ViewContext.Writer.WriteLine("</ul>");
            }

            ViewContext.Writer.WriteLine("<div class=\"tab-content\">");

            

            return this;
        }

        public class TabContent : ContainerBase
        {
            private bool _isActive = false;
            

            internal TabContent(string id,bool? isActive,string urlKey, ViewContext viewContext) : base(viewContext)
            {
                this.Css($"tab-pane {isActive.If("active")}");

                this.ID(id);

                this.Data("data-urlkey", urlKey);
                this.Data("data-activevalue", id);
            }

            public TabContent ActiveScript(string script)
            {
                if (!string.IsNullOrWhiteSpace(script))
                {
                    this.Attributes.Data("active", script);
                }
                

                return this;
            }

            public TabContent UnActiveScript(string script)
            {
                if (!string.IsNullOrWhiteSpace(script))
                {
                    this.Attributes.Data("unactive", script);
                }
                
                return this;
            }

            public override void Dispose()
            {
                ViewContext.Writer.WriteLine("</div> <!-- .tab-pane-inner -->");

                ViewContext.Writer.WriteLine("</div> <!-- .tab-pane -->");
            }

            internal override ContainerBase RenderInternal()
            {
                ViewContext.Writer.WriteLine($"<div {Attributes}>");

                ViewContext.Writer.WriteLine("<div class=\"tab-pane-inner\">");

                return this;
            }
        }
    }
}
